package com.anruisi.hxmes.gateway.service.impl;

import com.anruisi.hxmes.gateway.entity.MenuRoleVO;
import com.anruisi.hxmes.gateway.entity.MenuRoles;
import com.anruisi.hxmes.gateway.service.MenuRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author cmy
 * @date 2021/5/21 17:17
 */
@Service("menuRoleService")
public class MenuRoleServiceImpl implements MenuRoleService {

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Override
    public List<MenuRoles> getAllMenusWithRole() {

        System.out.println(jdbcTemplate.getDataSource().getClass().getName()+"----------------333333333333333333333333333333333");

        String sql = "select m.id,m.url,m.name,m.type,m.parentId,m.sort,r.name as roleName " +
                "from " +
                "sys_menu m,sys_menu_role mr,sys_role r " +
                "where " +
                "m.id=mr.mid and mr.rid=r.id " +
                "order by " +
                "m.type desc,m.parentId,m.sort desc";

        List<MenuRoleVO> menuRoleList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(MenuRoleVO.class));
        Map<Integer,MenuRoles> temp = new LinkedHashMap<>(menuRoleList.size());

        for (MenuRoleVO bean : menuRoleList) {
            if(temp.containsKey(bean.getId())){
                MenuRoles menuRoles = temp.get(bean.getId());
                menuRoles.getRoleName().add(bean.getRoleName());
            }else{
                List<String> roleNames = new ArrayList<>(1);
                roleNames.add(bean.getRoleName());
                MenuRoles menuRoles = new MenuRoles(bean.getId(),bean.getUrl(),roleNames);
                temp.put(bean.getId(),menuRoles);
            }
        }

        List<MenuRoles> result = new ArrayList<>(temp.values());
        return result;
    }

}
